<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>基本资料</span>
    </div>
    <!-- 表单 -->
    <el-form label-position="left" label-width="80px" :model="userInfo" :rules="formRules" ref="formRef">
      <el-form-item label="登录名称">
        <el-input disabled v-model="userInfo.username"></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="userInfo.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="userInfo.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="doEdit">提交修改</el-button>
        <el-button @click="$refs.formRef.resetFields()">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  name: "UserInfo",
  data() {
    return {
      //浅拷贝vuex中的数据 （只拷贝第一层。 相当于重新声明一个对象,把vuex里面的值放进去）
      userInfo: { ...this.$store.state.user },
      //表单校验
      formRules: {
        nickname: [
          { required: true, message: "请输入用户昵称", trigger: "blur" },
          {
            pattern: /^\S{1,10}$/,
            message: "昵称必须是1-10位的非空字符串",
            trigger: "blur"
          }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            type:'email',
            message: "邮箱格式不对",
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    doEdit(){
      //(1)判断表单校验成功
      this.$refs.formRef.validate(async valide =>{
        //(2)通过：发送ajax
        if(valide){
           const {data:res} = await this.$axios.put('/my/userinfo',this.userInfo)
           console.log(res)
           //提示
           this.$message.success( res.message )
           //成功，更新vuex
           if( res.code === 0 ){
             //用户信息放入vuex的actions中, 更新actions
             this.$store.dispatch('getUserInfo')
           }
           
        }
      })
    }
  },
};
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
